package org.goldfish.chatroom.controller;

import org.goldfish.chatroom.entity.PublicNetworkService;
import org.goldfish.chatroom.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.apache.logging.log4j.*;
import java.util.List;

@Controller
@RequestMapping("/info")
public class InfoListController {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private PublicNetworkServiceMapper publicNetworkServiceMapper;

    private static final Logger logger = LogManager.getLogger(InfoListController.class);

    @GetMapping
    public String infoList(Model model,
                           @RequestParam(
                                   name = "logout",
                                   defaultValue = "false"
                           )
                           String logout) {
        try {
            List<PublicNetworkService> services= publicNetworkServiceMapper.getPublicNetworkServiceList();
            model.addAttribute("networkServices", services);
            model.addAttribute("message_details", messageMapper.getMessageDetails());
            return "info";
        } catch (Exception e) {
            logger.warn("Failed to get network services", e);
            model.addAttribute("error", e.getMessage());
            return "error";
        }
    }

    @PostMapping
    public String infoListRaw(Model model) {
        return infoList(model,"false");
    }

    @GetMapping("delete")
    public String deleteInfo(
            @RequestParam(
                    name = "service_name"
            )
            String service_name) {
        try {
            publicNetworkServiceMapper.deletePublicNetworkService(service_name);
            return "redirect:../info";
        } catch (Exception e) {
            logger.warn("Failed to delete network service", e);
            return "error";
        }
    }
}
